package com.jacky.iot;

import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.core.coap.OptionSet;
import org.eclipse.californium.core.config.CoapConfig;
import org.eclipse.californium.elements.config.Configuration;
import org.eclipse.californium.elements.config.UdpConfig;
import org.eclipse.californium.elements.exception.ConnectorException;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class HelloWorldClient {

    private static final File CONFIG_FILE = new File("Californium3.properties");
    private static final String CONFIG_HEADER = "Californium CoAP Properties file for client";
    private static final int DEFAULT_MAX_RESOURCE_SIZE = 2 * 1024 * 1024; // 2 MB
    private static final int DEFAULT_BLOCK_SIZE = 512;

    static {
        CoapConfig.register();
        UdpConfig.register();
    }

    private static Configuration.DefinitionsProvider DEFAULTS = new Configuration.DefinitionsProvider() {

        @Override
        public void applyDefinitions(Configuration config) {
            config.set(CoapConfig.MAX_RESOURCE_BODY_SIZE, DEFAULT_MAX_RESOURCE_SIZE);
            config.set(CoapConfig.MAX_MESSAGE_SIZE, DEFAULT_BLOCK_SIZE);
            config.set(CoapConfig.PREFERRED_BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
        }
    };

    public static void main(String[] args) throws URISyntaxException, ConnectorException, IOException {
        Configuration config = Configuration.createWithFile(CONFIG_FILE, CONFIG_HEADER, DEFAULTS);
        Configuration.setStandard(config);

        URI url = new URI("coap://localhost:5683/helloWorld");
        CoapClient client = new CoapClient();
        client.setURI(url.toString());
        CoapResponse resp = client.get();
        System.out.println("options: \n" + resp.getOptions());
        System.out.println("pretty response: \n" + Utils.prettyPrint(resp));

        System.out.println("\n------------------- pub -------------------\n");
        client.setURI("coap://localhost:5683/pub");

        CoapResponse pubResp = client.get();
        System.out.println("options: \n" + pubResp.getOptions());
        System.out.println("pretty response: \n" + Utils.prettyPrint(pubResp));
    }
}
